﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace FGUFW.Play.StepGrid
{
    public class GridView : MonoBehaviour,IPointerDownHandler
    {
        public Vector2Int Grid;
        DefaultModeModule _module;
        RectTransform _rectTransform;
        float _gameViewSize;
        Image _image;

        // Start is called before the first frame update
        void Start()
        {
            _module = StepGridPlayManager.I.Module<DefaultModeModule>();
            _rectTransform = transform as RectTransform;
            _gameViewSize = (transform.parent as RectTransform).rect.height;
            _image = GetComponent<Image>();
        }

        // Update is called once per frame
        void Update()
        {
            var pos = _rectTransform.anchoredPosition;
            pos.y -= _module.Speed*_gameViewSize*Time.deltaTime;
            if(pos.y<-_rectTransform.rect.height)
            {
                if(Grid.y==_module.Grids[Grid.x%_module.Grids.Length])
                {
                    _module.OnLineEnd(Grid.x,!_image.raycastTarget);
                }
                pos.y+=_gameViewSize+_rectTransform.rect.height;

                Grid.x+=5;
                if(Grid.y==_module.Grids[Grid.x%_module.Grids.Length])
                {
                    setColor(Color.black);
                }
                else
                {
                    setColor(Color.white);
                }
                _image.raycastTarget=true;
                // Debug.Log(name);
            }
            _rectTransform.anchoredPosition = pos;
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            _module.OnClickGrid(Grid);
            setColor(new Color32(128,128,128,255));
            _image.raycastTarget=false;
            // Debug.LogWarning(name);
        }

        void setColor(Color color)
        {
            _image.color = color;
        }
    }
}
